﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// 屏幕键盘控制帮助类
    /// </summary>
    public class TouchKeyBoardHelper
    {

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);
        private const UInt32 WM_SYSCOMMAND = 0x112;                                                    //系统命令消息
        private const UInt32 SC_RESTORE = 0xf120;                                                      //恢复窗口命令
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);       //系统发送消息API
        private const string OnScreenKeyboadApplication = "osk.exe";                                   // 屏幕键盘应用程序名

        /// <summary>
        /// 启用系统键盘
        /// </summary>
        /// <param name="msg">返回的消息，如果发生错误则包含错误信息</param>
        /// <returns>操作结果</returns>
        public static bool OpenKeyBoardFun(out string msg)
        {
            msg = string.Empty;
            try
            {
                // 检查是否有正在运行的键盘进程
                Process[] pro = Process.GetProcessesByName("osk");

                //获取键盘应用程序名
                string processName = System.IO.Path.GetFileNameWithoutExtension(OnScreenKeyboadApplication);
                var processList = new List<Process>(Process.GetProcesses());
                // 检测键盘应用是否运行
                var query = processList.FindAll((u) => u.ProcessName == processName);
                Process keyboardProcess = null;
                if (query != null && query.Count > 0)
                {
                    keyboardProcess = query[0];
                }

                //如果键盘程序为空,创建一个实例,否则直接前台显示
                if (keyboardProcess == null)
                {
                    IntPtr ptr = new IntPtr(); ;
                    bool sucessfullyDisabledWow64Redirect = false;

                    //判断当前系统是否为64位系统
                    if (Is64BitOperatingSystem)
                    {
                        sucessfullyDisabledWow64Redirect = Wow64DisableWow64FsRedirection(ref ptr);
                    }

                    using (Process osk = new Process())
                    {
                        osk.StartInfo.FileName = OnScreenKeyboadApplication;
                        osk.Start();
                    }
                    // 恢复文件系统重定向
                    if (Is64BitOperatingSystem)
                        if (sucessfullyDisabledWow64Redirect)
                            Wow64RevertWow64FsRedirection(ptr);
                }
                else
                {
                    //唤起键盘界面前台显示
                    var windowHandle = keyboardProcess.MainWindowHandle;
                    SendMessage(windowHandle, WM_SYSCOMMAND, new IntPtr(SC_RESTORE), new IntPtr(0));
                }

            }
            catch (Exception ex)
            {
                msg = ex.ToString();
                return false;
            }
            return true;
        }


        /// <summary>
        ///  关闭系统软键盘
        /// </summary>
        /// <param name="msg">返回的消息，如果发生错误则包含错误信息</param>
        /// <returns>操作是否成功</returns>
        public static bool CloseKeyBoardFun(out string msg)
        {
            msg = string.Empty;
            try
            {
                // 获取键盘的进程
                Process[] pros = Process.GetProcessesByName("osk");
                foreach (Process p in pros)
                {
                    //检查是否在运行
                    if (!p.HasExited)
                    {
                        // 尝试优雅地关闭主窗口
                        if (!p.CloseMainWindow())
                        {
                            // 如果失败，则强制终止进程
                            p.Kill();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.ToString();
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检测操作系统是否为64位
        /// </summary>
        private static bool Is64BitOperatingSystem
        {
            get
            {
                //方法1：手动查询校验系统版本
                //try
                //{
                //    string addressWidth = String.Empty;
                //    ConnectionOptions mConnOption = new ConnectionOptions();
                //    ManagementScope mMs = new ManagementScope("//localhost", mConnOption);
                //    ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor");
                //    ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery);
                //    ManagementObjectCollection mObjectCollection = mSearcher.Get();
                //    foreach (ManagementObject mObject in mObjectCollection)
                //    {
                //        addressWidth = mObject["AddressWidth"].ToString();
                //    }
                //    return addressWidth == "64";
                //}
                //catch (Exception ex)
                //{

                //    return false;
                //}

                //方法2：使用 .NET 提供的内置方法检测操作系统是否为64位
                try
                {
                    return Environment.Is64BitOperatingSystem;
                }
                catch (Exception)
                {
                    // 如果检测失败，默认返回 false
                    return false;
                }
            }
        }




    }
}
